package com.yfbao.encryptor;

import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;

@Component
public class AESEncryptor {

    private static final String ALGORITHM = "AES";
    private static final String TRANSFORMATION = "AES/CBC/PKCS5Padding";
    private static final String SECRET_KEY = "xK3mN8pQ2vR9sT4w"; // 16位密钥

    private SecretKeySpec secretKey;
    private IvParameterSpec iv;

    @PostConstruct
    public void init() {
        try {
            // 实际项目中建议从配置中心或环境变量获取
            String keyStr = SECRET_KEY;
            byte[] key = keyStr.getBytes(StandardCharsets.UTF_8);

            // 验证密钥长度
            if (key.length != 16) {
                throw new IllegalArgumentException("AES密钥长度必须为16字节");
            }

            this.secretKey = new SecretKeySpec(key, ALGORITHM);

            // 使用固定的IV（实际项目中建议动态生成）
            byte[] ivBytes = new byte[16];
            Arrays.fill(ivBytes, (byte) 0);
            this.iv = new IvParameterSpec(ivBytes);
        } catch (Exception e) {
            throw new RuntimeException("初始化加密工具失败", e);
        }
    }

    public String encrypt(String data) {
        if (data == null) return null;
        try {
            Cipher cipher = Cipher.getInstance(TRANSFORMATION);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
            byte[] encrypted = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
            return Base64.getEncoder().encodeToString(encrypted);
        } catch (Exception e) {
            throw new RuntimeException("加密失败", e);
        }
    }

    public String decrypt(String encryptedData) {
        if (encryptedData == null) return null;
        try {
            Cipher cipher = Cipher.getInstance(TRANSFORMATION);
            cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
            byte[] decoded = Base64.getDecoder().decode(encryptedData);
            byte[] decrypted = cipher.doFinal(decoded);
            return new String(decrypted, StandardCharsets.UTF_8);
        } catch (Exception e) {
            throw new RuntimeException("解密失败", e);
        }
    }
}
